package com.leetcode.LC_MED;

public class LC617 {
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {

        if (root1 == null) {
            return root2;
        } else if (root2 == null) {
            return root1;
        }
        dfs(root1, root2);
        return root1;
    }

    private void dfs(TreeNode root1, TreeNode root2) {
        if (root1 == null && root2 == null) {//都为空
            return;
        }
        if (root1 != null && root2 != null) {//都不为空
            root1.val += root2.val;
        }
        if (root1.left != null && root2.left != null) {//左不为空
            dfs(root1.left, root2.left);
        }
        if (root1.right != null && root2.right != null) {//右不为空
            dfs(root1.right, root2.right);
        }
        if (root1.left == null && root2.left != null) {
            root1.left = root2.left;
        }
        if (root1.right == null && root2.right != null) {
            root1.right = root2.right;
        }
    }

    public TreeNode mergeTrees2(TreeNode t1, TreeNode t2) {

        if (t1 == null) {
            return t2;
        }
        if (t2 == null) {
            return t1;
        }

        TreeNode treeNode = new TreeNode(t1.val + t1.val);
        treeNode.left = mergeTrees2(t1.left, t2.left);
        treeNode.right = mergeTrees2(t1.right, t2.right);
        return treeNode;
    }

}
